/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Client;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.lang.System.exit;
import java.rmi.RemoteException;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import static javax.swing.SwingUtilities.isRightMouseButton;
import rmip.ServerInt;

/**
 *
 * @author Abdo
 */
public class ChatWin extends javax.swing.JFrame {
    ServerInt si;
    String nickName;
    String mail;
    int id;
    ClientImp user;
    Hashtable friends;
    Hashtable on;
    private Enumeration e;
    DefaultListModel<User> model = new DefaultListModel<>();
    /**
     * Creates new form ChatWin
     * @param mail
     * @param si
     */
    public ChatWin(String mail,ServerInt si,ClientImp cli) {
        initComponents();
        try {
            this.si = si;
            nickName=si.getNickName(mail);
            id=si.getId(mail);
            this.user=cli;
            this.mail=mail;
            jList1.setCellRenderer(new MyListRenderer());
            repaintList();
        } catch (RemoteException ex) {
            Logger.getLogger(ChatWin.class.getName()).log(Level.SEVERE, null, ex);
        }
        jLabel2.setText(nickName);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu = new javax.swing.JPopupMenu();
        sendMail = new javax.swing.JMenuItem();
        jPanel2 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel(nickName);
        jButton1 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        add = new javax.swing.JButton();
        groupChat = new javax.swing.JButton();
        groupChat1 = new javax.swing.JButton();
        jComboBox2 = new javax.swing.JComboBox();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList(model);

        sendMail.setText("Send Email ...");
        sendMail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendMailActionPerformed(evt);
            }
        });
        jPopupMenu.add(sendMail);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Chat W Laban");
        setMinimumSize(new java.awt.Dimension(350, 500));
        setPreferredSize(new java.awt.Dimension(350, 700));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel2.setLayout(new java.awt.GridLayout(2, 1));

        jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 20)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(51, 51, 255));
        jLabel1.setText("Welcome");
        jPanel6.add(jLabel1);

        jLabel2.setFont(new java.awt.Font("Segoe UI Symbol", 0, 20)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(51, 51, 255));
        jPanel6.add(jLabel2);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/logout.png"))); // NOI18N
        jButton1.setToolTipText("logout");
        jButton1.setMargin(new java.awt.Insets(2, 4, 2, 4));
        jButton1.setMaximumSize(new java.awt.Dimension(50, 50));
        jButton1.setMinimumSize(new java.awt.Dimension(40, 40));
        jButton1.setPreferredSize(new java.awt.Dimension(40, 40));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel6.add(jButton1);

        jPanel2.add(jPanel6);

        add.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/gtk-add.png"))); // NOI18N
        add.setMargin(new java.awt.Insets(2, 2, 2, 2));
        add.setMaximumSize(new java.awt.Dimension(40, 40));
        add.setMinimumSize(new java.awt.Dimension(40, 40));
        add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addActionPerformed(evt);
            }
        });
        jPanel3.add(add);
        add.setToolTipText("Add new contact");

        groupChat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/group.png"))); // NOI18N
        groupChat.setMargin(new java.awt.Insets(2, 2, 2, 2));
        groupChat.setMaximumSize(new java.awt.Dimension(40, 40));
        groupChat.setMinimumSize(new java.awt.Dimension(40, 40));
        groupChat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                groupChatActionPerformed(evt);
            }
        });
        jPanel3.add(groupChat);
        groupChat.setToolTipText("Start conference");

        groupChat1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/sendMail.png"))); // NOI18N
        groupChat1.setToolTipText("Send Mail");
        groupChat1.setMargin(new java.awt.Insets(2, 2, 2, 2));
        groupChat1.setMaximumSize(new java.awt.Dimension(40, 40));
        groupChat1.setMinimumSize(new java.awt.Dimension(40, 40));
        groupChat1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                groupChat1ActionPerformed(evt);
            }
        });
        jPanel3.add(groupChat1);
        groupChat.setToolTipText("Start conference");

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Available", "Busy", "Away" }));
        jComboBox2.setPreferredSize(new java.awt.Dimension(100, 30));
        jComboBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox2ActionPerformed(evt);
            }
        });
        jPanel3.add(jComboBox2);

        jPanel2.add(jPanel3);

        getContentPane().add(jPanel2, java.awt.BorderLayout.NORTH);

        jPanel5.setLayout(new java.awt.BorderLayout());

        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jList1.setAutoscrolls(false);
        jList1.setFixedCellWidth(120);
        jList1.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
            public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                jList1MouseWheelMoved(evt);
            }
        });
        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jList1MousePressed(evt);
            }
        });
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        jPanel5.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel5, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void repaintList(){
        User userObj;
        try {
            model.removeAllElements();
            friends=si.getFriends(mail);
            on=si.onlineFriends(mail);
            e = friends.keys();
            while (e.hasMoreElements()){
                Object o = e.nextElement();
                //System.out.println(o.toString());
               if(on.containsKey(o)){
                   //System.out.println(on.get(o).toString()+"\n");
                   userObj = new User(o.toString(),on.get(o).toString());
               } 
               else{
                   userObj = new User(o.toString(),"offline");
                   //System.out.println("offline\n");
               }   
                    model.addElement(userObj);
            }
            //JOptionPane.showMessageDialog(null, "You have registered sucessfully" , "Chat W Laban", JOptionPane.PLAIN_MESSAGE);
        } catch (RemoteException ex) {
            Logger.getLogger(ChatWin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void groupChatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_groupChatActionPerformed
        try {
            String chatname=new Date().toString()+mail;
            Vector<String> group=new Vector<String>();
            group.add(mail);
            user.startNewGroupChat(chatname, mail, si);
            
        } catch (RemoteException ex) {
            Logger.getLogger(ChatWin.class.getName()).log(Level.SEVERE, null, ex);
        }
      
    }//GEN-LAST:event_groupChatActionPerformed

    private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed
        // TODO add your handling code here:
        new AddFriend(si,mail,this).setVisible(true);
    }//GEN-LAST:event_addActionPerformed

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged

    }//GEN-LAST:event_jList1ValueChanged

    private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
        
        if(evt.getClickCount()==2)
        {
        try {
          
            user.convGui(this.mail, jList1.getSelectedValue().toString(), si);
            
            
        } catch (RemoteException ex) {
            Logger.getLogger(ChatWin.class.getName()).log(Level.SEVERE, null, ex);
        }        // TODO add your handling code here:
        }
    }//GEN-LAST:event_jList1MouseClicked

    private void jList1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MousePressed
        // TODO add your handling code here:
    }//GEN-LAST:event_jList1MousePressed

    private void sendMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendMailActionPerformed
        // TODO add your handling code here:
        new SendMail(mail,jList1.getSelectedValue().toString(),si).setVisible(true);
    }//GEN-LAST:event_sendMailActionPerformed

    private void groupChat1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_groupChat1ActionPerformed
        // TODO add your handling code here:
        if(!jList1.isSelectionEmpty())sendMail.doClick();
    }//GEN-LAST:event_groupChat1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            si.signOut(mail);
            exit(0);
        } catch (RemoteException ex) {
            Logger.getLogger(ChatWin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
                try {
            si.signOut(mail);
            exit(0);
        } catch (RemoteException ex) {
            Logger.getLogger(ChatWin.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_formWindowClosing

    private void jList1MouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_jList1MouseWheelMoved
        // TODO add your handling code here:
    }//GEN-LAST:event_jList1MouseWheelMoved

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
        try {
            // TODO add your handling code here:
            si.setStatus(mail, jComboBox2.getSelectedItem().toString());
        } catch (RemoteException ex) {
            Logger.getLogger(ChatWin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jComboBox2ActionPerformed

   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ChatWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ChatWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ChatWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ChatWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton add;
    private javax.swing.JButton groupChat;
    private javax.swing.JButton groupChat1;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPopupMenu jPopupMenu;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuItem sendMail;
    // End of variables declaration//GEN-END:variables

}
class PopUpDemo extends JPopupMenu {
    
    JMenuItem chatItem;
    JMenuItem mailItem;
    JMenuItem deleteItem;
    
    public PopUpDemo(){
        chatItem = new JMenuItem("Open private chat");
        mailItem = new JMenuItem("Send email...");
        deleteItem = new JMenuItem("Delete contact");
        add(chatItem);
        add(mailItem);
        add(deleteItem);
    }
}
class User{
    String userMail,userStatus;
    public User(String userMail,String userStatus){
        this.userMail=userMail;
        this.userStatus=userStatus;
    }
    @Override
    public String toString(){
        return userMail;
    }
    public String getStatus(){
        return userStatus;
    }
}
class MyListRenderer extends JLabel implements ListCellRenderer<User> {
 
    @Override
    public Component getListCellRendererComponent(JList<? extends User> list, User value, int index, boolean isSelected, boolean cellHasFocus) {
 //JLabel label = (JLabel)super.getListCellRendererComponent((JList)list,(Object)value,index,isSelected,cellHasFocus);
        String code = value.getStatus();
        ImageIcon imageIcon = new ImageIcon(getClass().getResource("/images/"+code+".png"));        
        setIcon(imageIcon);
        setText(value.toString());
        Color background;
         Color foreground;

         // check if this cell represents the current DnD drop location
         JList.DropLocation dropLocation = list.getDropLocation();
         if (dropLocation != null
                 && !dropLocation.isInsert()
                 && dropLocation.getIndex() == index) {

             background = Color.BLUE;
             foreground = Color.WHITE;

         // check if this cell is selected
         } else if (isSelected) {
             background = Color.RED;
             foreground = Color.RED;

         // unselected, and not the DnD drop location
         } else {
             background = Color.WHITE;
             foreground = Color.BLACK;
         };

         setBackground(background);
         setForeground(foreground);
        return this;
    }
}